# coding=utf-8
import requests
from typing import Union
from . import logger


def reverse_ip_location(ip: str) -> Union[dict, None]:
    try:
        r = requests.get(url='http://ip.api.apistore.cn/ip',
                         params={'ip': ip},
                         headers={'Authorization': 'APPCODE a60d280f5b4f421c838bbebde1f928ed'},
                         timeout=1)
        if r.status_code < 300:
            json = r.json()
            if json['error_code'] == 0:
                return json['result']
        logger.info("reverse ip content:" + r.text)
    except Exception as e:
        logger.error("reverse ip error:" + str(e))
        return None
    return None


def reverse_ip_location_v2(ip: str) -> Union[dict, None]:
    try:
        r = requests.get(url='http://aliyun.api.caacbook.com.cn/RTBAsia/ip_location',
                         params={'ip': ip},
                         headers={'Authorization': 'APPCODE a60d280f5b4f421c838bbebde1f928ed'},
                         timeout=1)
        if r.status_code < 300:
            json = r.json()
            if json['code'] == 200:
                return json['location']
        logger.info("reverse ip content:" + r.text)
    except Exception as e:
        logger.error("reverse ip error:" + str(e))
        return None
    return None


def reverse_ip_district(ip: str) -> Union[dict, None]:
    try:
        r = requests.get(url='http://aliyun.api.caacbook.com.cn/RTBAsia/ip_district',
                         params={'ip': ip},
                         headers={'Authorization': 'APPCODE a60d280f5b4f421c838bbebde1f928ed'},
                         timeout=1)
        if r.status_code < 300:
            json = r.json()
            if json['code'] == 200:
                return json['districts']
        logger.info("reverse district content:" + r.text)
    except Exception as e:
        logger.error("reverse district error:" + str(e))
        return None
    return None
